package LockTest;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 李泽伟
 */
public class LockTest {
    public static void main(String[] args) {
        Windows w = new Windows();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);
        t1.setName("线程1");
        t2.setName("线程2");
        t3.setName("线程3");
        t1.start();
        t2.start();
        t3.start();
    }
}

class Windows implements Runnable{
    private int ticket = 100;
    /**
     * 1.实例化ReentrantLock对象
     */
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                //2.调用lock方法
                lock.lock();
                if(ticket>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName()+":"+ticket);
                    ticket--;
                }else {
                    break;
                }
            }finally {
                //3.调用解锁方法
                lock.unlock();
            }

        }
    }
}